<?php
namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use app\facade\Redisearch;
use app\model\City;
use app\helper\Arr;

class Cache extends Command
{
    protected function configure()
    {
        $this->setName('redisearch')
            ->addArgument('name', Argument::OPTIONAL, "your name")
            ->addOption('city', null, Option::VALUE_REQUIRED, 'city name')
            ->setDescription('redisearch');
    }

    protected function execute(Input $input, Output $output)
    {
        // redis()->flushdb();
        // Redisearch::drop(City::$scoutIndex);
        Redisearch::create(City::$scoutIndex, ['id'=>'text', 'name'=>'text', 'pid'=>'text']);
        $rows = City::field(City::$scoutField)->select()->toArray();
        $this->hmset(City::$scoutIndex, $rows);
        $views = City::all(array_column($rows, 'item_id'), City::$scoutField);
        /*
        $roots = Root::views(array_column($views, 'root_id'), ['cate_id']);
        $items = Arr::merge($views, $roots, 'root_id');
        foreach($rows as $k => $row){
            if(isset($items[$row['item_id']])){
                $item = $items[$row['item_id']];
                $rows[$k] += ['cate_id' => $item['cate_id']];
            }
        }
        $this->hmset(CityItem::$scoutIndex, array_values($rows));
        */
    }
    // 
    private function hmset($index, $rows = []){
        $l = count($rows) - 1;
        foreach($rows as $i => $row){
            if($i == 0 || $i % 100 == 0){
                $mult = redis()->multi();
            }
            $mult->hmset($index . ':' . $row['id'], array_map(fn($v)=>is_array($v)?json_encode($v):$v, $row));
            if($i == $l || $i % 100 == 99){
                $mult->exec();
            }
        }
    }
}